﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace DllCallAnalysis45.Helpers
{
    public static class FileCheckHelper
    {
        public static string GetFileSha512(string filePath)
        {
            using (SHA512 mySHA512 = new SHA512Managed())
            {
                // 为文件创建一个fileStream。
                using (FileStream fileStream = File.OpenRead(filePath))
                {
                    byte[] hashValue = mySHA512.ComputeHash(fileStream);

                    var sb = new StringBuilder();

                    for (int i = 0; i < hashValue.Length; i++)
                    {
                        sb.Append($"{hashValue[i]:X2}");
                    }

                    return sb.ToString();
                }
            }
        }

        public static bool CreateFileSha512CheckFile(string filePath, string checkFilePath)
        {
            if (File.Exists(filePath) != true)
                return false;

            var check = GetFileSha512(filePath);
            var obj = new
            {
                version = 1,
                contentHash = check,
            };

            File.WriteAllText(checkFilePath, JsonConvert.SerializeObject(obj), Encoding.UTF8);
            return true;
        }
    }
}
